package main

import (
	"fiberdemo/app/db"
	"fiberdemo/config"
	"fiberdemo/routes"
	"flag"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cache"
	"github.com/gofiber/fiber/v2/middleware/compress"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/csrf"
	"github.com/gofiber/fiber/v2/middleware/favicon"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/fiber/v2/middleware/recover"
	"log"
	"os"
)

func main() {
	flag.Parse()

	config.InitConfig()

	db.InitDB()
	db.InitCache()

	app := fiber.New()

	//panic恢复 Default middleware config
	app.Use(recover.New())

	//HTTP缓存 Initialize default config
	app.Use(cache.New())
	// Or extend your config for customization
	//app.Use(cache.New(cache.Config{
	//	Next: func(c *fiber.Ctx) bool {
	//		return c.Query("refresh") == "true"
	//	},
	//	Expiration:   30 * time.Minute,
	//	CacheControl: true,
	//}))

	//压缩 Default middleware config
	app.Use(compress.New())

	// Provide a custom compression level
	//app.Use(compress.New(compress.Config{
	//	Level: compress.LevelBestSpeed, // 1
	//}))

	// Skip middleware for specific routes
	//app.Use(compress.New(compress.Config{
	//	Next:  func(c *fiber.Ctx) bool {
	//		return c.Path() == "/dont_compress"
	//	},
	//	Level: compress.LevelBestSpeed, // 1
	//}))

	// 跨域 Default config
	app.Use(cors.New())

	// Or extend your config for customization
	//app.Use(cors.New(cors.Config{
	//	AllowOrigins: "https://gofiber.io, https://gofiber.net",
	//	AllowHeaders:  "Origin, Content-Type, Accept",
	//}))

	//CSRF防护 Initialize default config
	app.Use(csrf.New())

	// Or extend your config for customization
	//app.Use(csrf.New(csrf.Config{
	//	KeyLookup:      "header:X-Csrf-Token",
	//	CookieName:     "csrf_",
	//	CookieSameSite: "Strict",
	//	Expiration:     1 * time.Hour,
	//	KeyGenerator:   utils.UUID,
	//}))

	//favicon配置 Provide a minimal config
	app.Use(favicon.New())

	// Or extend your config for customization
	//app.Use(favicon.New(favicon.Config{
	//	File: "./favicon.ico",
	//}))

	//HTTP日志 Default middleware config
	//app.Use(logger.New())

	//自定义日志格式
	//app.Use(logger.New(logger.Config{
	//	Format:     "${pid} ${status} - ${method} ${path}\n",
	//	TimeFormat: "02-Jan-2006",
	//	TimeZone:   "America/New_York",
	//}))

	//自定义日志写入文件
	file, err := os.OpenFile("./tmp/req.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("error opening file: %v", err)
	}
	defer file.Close()

	app.Use(logger.New(logger.Config{
		Output: file,
	}))

	app.Static("/", "./public")

	routes.InitRoute(app)

	log.Fatal(app.Listen(":3000"))
}
